package com.rednote.controller;

import com.rednote.common.Result;
import com.rednote.common.UserContextHolder;
import com.rednote.entity.vo.FollowUserVO;
import com.rednote.service.UserFollowService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;
import com.rednote.common.JwtUtil;
import com.rednote.entity.UserFollow;
import java.util.List;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

/**
 * 用户关注控制层
 */
@RestController
@RequestMapping("/userFollows")
public class UserFollowController {

    @Resource
    private UserFollowService userFollowService;
    
    @Resource
    private JwtUtil jwtUtil;


    /**
     * 关注用户
     * @param userId 被关注用户的ID
     * @return 关注结果
     */
    @PostMapping("/follow")
    public Result<?> followUser(@RequestParam Integer userId) {
        try {
            userFollowService.follow(userId);
            return Result.success("关注成功");
        } catch (Exception e) {
            return Result.fail("关注失败: " + e.getMessage());
        }
    }

    /**
     * 取消关注用户
     * @param userId 被取消关注用户的ID
     * @return 取消关注结果
     */
    @DeleteMapping("/follow")
    public Result<?> unfollowUser(@RequestParam Integer userId) {
        try {
            userFollowService.unfollow(userId);
            return Result.success("取消关注成功");
        } catch (Exception e) {
            return Result.fail("取消关注失败: " + e.getMessage());
        }
    }


    /**
     * 判断是否已关注用户
     * @param followedUserId 被关注用户的ID
     * @return 是否已关注
     */
    @GetMapping("/isFollowed")
    public Result<?> isFollowed(@RequestParam Integer followedUserId) {
        boolean followed = userFollowService.isFollowed(followedUserId);
        return Result.success(followed);
    }

    // 获取当前用户的关注列表
    @GetMapping("/my-follows")
    public Result<?> getMyFollows(@RequestParam(defaultValue = "1") Integer page,
                                  @RequestParam(defaultValue = "10") Integer size) {
        try {
            Integer userId = UserContextHolder.getUserId();
            if (userId == null) {
                return Result.fail("用户未登录或未提供有效的用户ID");
            }
            Page<FollowUserVO> pageResult = userFollowService.listUserFollows(userId, page, size);
            return Result.success(pageResult); 
        } catch (Exception e) {
            return Result.fail("获取关注列表失败: " + e.getMessage());
        }
    }

    // 获取某用户的关注列表
    @GetMapping("/sb-follows")
    public Result<?> getSbFollows(@RequestParam Integer userId,
                                    @RequestParam(defaultValue = "1") Integer page,
                                  @RequestParam(defaultValue = "10") Integer size) {
        try {
            Page<FollowUserVO> pageResult = userFollowService.listUserFollows(userId, page, size);
            return Result.success(pageResult);
        } catch (Exception e) {
            return Result.fail("获取关注列表失败: " + e.getMessage());
        }
    }
}
